package com.sfx.算法专题.滑动窗口.变化窗口;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-08-07
 * Time: 12:48
 */
public class Code_5_totalFruit {

    static class Solution {
        public int totalFruit(int[] fruits) {
            Map<Integer, Integer> map = new HashMap<>();
            int left = 0;
            int right = 0;
            int n = fruits.length;
            int res = 0;
            while (right < n) {
                if (map.get(fruits[right]) == null) {
                    map.put(fruits[right], 1);
                } else {
                    map.put(fruits[right], map.get(fruits[right]) + 1);
                }
                //map.put(fruits[right],map.getOrDefault(map.get(fruits[right]),0)+1);
                while (map.size() > 2 && left < right) {
                    map.put(fruits[left], map.getOrDefault(map.get(fruits[left]), 0) - 1);
                    if (map.get(fruits[left]) <= 0) {
                        map.remove(fruits[left]);
                    }
                    left++;
                }
                res = Math.max(res, right - left + 1);
                right++;
            }
            return res;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] fruits = new int[]{3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4};
        solution.totalFruit(fruits);
    }
}